package com.web.base.auth.util;

import com.web.base.auth.message.MenuRequest;
import com.web.base.auth.message.MenuResponse;
import com.web.base.auth.model.Menu;
import com.web.base.auth.model.MenuAuth;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜单转换器
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2017年04月15日
 */
public class MenuConvertor
{
	private MenuConvertor()
	{
	}
	
	public static Menu toMenu(MenuRequest request)
	{
		if (request == null)
			return null;
		
		Menu menu = new Menu();
		menu.setId(request.getId());
		menu.setParentId(request.getParentId());
		menu.setAppId(request.getAppId());
		menu.setName(request.getName());
		menu.setUrl(request.getUrl());
		menu.setDescp(request.getDescp());
		menu.setState(request.getState());
		menu.setSort(request.getSort());
		menu.setAuths(request.getAuths());
		menu.setButtons(request.getButtons());
		return menu;
	}
	
	public static MenuResponse toResponse(Menu menu, List<MenuAuth> authList)
	{
		if (menu == null)
			return null;
		
		MenuResponse response = new MenuResponse();
		response.setId(menu.getId());
		response.setParentId(menu.getParentId());
		response.setAppId(menu.getAppId());
		response.setName(menu.getName());
		response.setUrl(menu.getUrl());
		response.setDescp(menu.getDescp());
		response.setState(menu.getState());
		response.setSort(menu.getSort());
		response.setAuths(menu.getAuths());
		response.setButtons(menu.getButtons());
		response.setSelected(menu.getSelected());
		response.setAuthList(MenuAuthConvertor.toResponse(authList));
		return response;
	}
	
	public static List<MenuResponse> toResponse(List<Menu> list, Map<Integer, List<MenuAuth>> authMap)
	{
		List<MenuResponse> responseList = new ArrayList<>();
		if (list == null || list.isEmpty())
			return responseList;
		
		for (Menu menu : list)
		{
			responseList.add(toResponse(menu, authMap == null ? null : authMap.get(menu.getId())));
		}
		return responseList;
	}
	
	public static Map<String, List<MenuResponse>> toResponse(Map<String, List<Menu>> map, List<MenuAuth> authList)
	{
		Map<String, List<MenuResponse>> responseMap = new HashMap<>();
		if (map == null || map.isEmpty())
			return responseMap;
		
		Map<Integer, List<MenuAuth>> authMap = null;
		if (authList != null && !authList.isEmpty())
		{
			authMap = authList.stream().collect(Collectors.groupingBy(MenuAuth::getMenuId));
		}
		for (Map.Entry<String, List<Menu>> entry : map.entrySet())
		{
			responseMap.put(entry.getKey(), toResponse(entry.getValue(), authMap));
		}
		return responseMap;
	}
	
}
